package com.icebergteam.warfacewidget.core.asynctaskmanager;

import android.os.AsyncTask;

public abstract class Task extends AsyncTask<String, TaskProgress, Integer> {
	protected Integer result;
	private boolean cancelableTask = true;
	private TaskProgress progressMessage;
	protected IProgressTracker progressTracker;
	private IHandleMessage handleMessage;
	
	public static final int CODE_ERROR = 0;
	public static final int CODE_OK = 1;
	public static final int CODE_CANCELED = 2;

	@Override
	protected abstract Integer doInBackground(String... arg0);

	@Override
	protected void onPostExecute(Integer _result) {
		// Update result
		result = _result;
		// And send it to progress tracker
		if (progressTracker != null) {
			progressTracker.onComplete(this.getClass().getCanonicalName(),
					this.getOnCompleteParams());
		}
		// Detach from progress tracker
		progressTracker = null;
	}

	public Task(TaskProgress message, IHandleMessage _handleError) {
		progressMessage = message;
		handleMessage = _handleError;
	}
	
	public Task(TaskProgress message, IHandleMessage _handleError, IProgressTracker _progressTracker) {
		progressMessage = message;
		handleMessage = _handleError;
		progressTracker = _progressTracker;
	}

	public void setProgressTracker(IProgressTracker _progressTracker) {
		// Attach to progress tracker
		progressTracker = _progressTracker;
		// Initialise progress tracker with current task state
		if (progressTracker != null) {
			
			if (result != null) {
				progressTracker.onComplete(this.getClass().getCanonicalName(),
						this.getOnCompleteParams());
			}
		}
	}

	

	@Override
	protected void onCancelled() {
		// Detach from progress tracker
		progressTracker.onCanceled(this.getClass().getCanonicalName(),
				this.getOnCanceledParams());
		progressTracker = null;
	}

	@Override
	protected void onProgressUpdate(TaskProgress... values) {
		// Update progress message
		progressMessage = values[0];
		// And send it to progress tracker
		if (progressTracker != null) {
			progressTracker.onProgress(progressMessage);
		}
	}

	protected void handleMessage(String title, String string) {
		if (handleMessage != null) {
			handleMessage.handleMessage(title, string);
		}
	}
	
	protected void handleError(String title, String string) {
		if (handleMessage != null) {
			handleMessage.handleError(title, string);
		}
	}
	
	public boolean isCancelableTask() {
		return cancelableTask;
	}

	public void setCancelableTask(boolean cancelableTask) {
		this.cancelableTask = cancelableTask;
	}

	public Object[] getOnCompleteParams() {
		return null;
	}

	public Object[] getOnCanceledParams() {
		return null;
	}

	public TaskProgress getProgressMessage() {
		return progressMessage;
	}

	@Override
	protected void onPreExecute() {
		if(progressMessage!= null){
			 progressTracker.onProgress(progressMessage);
		}
	}
}